<template>
    <view class="content">
        <view class="class1">
            <!-- examine 1待审核 2通过 3驳回 -->
            <view class="top" v-if="data.examine == 1">
                <image src="../../static/icon/wait.png" class="top-icon"></image>
                <view class="top-tit">待审核</view>
            </view>
            <view class="top" v-if="data.examine == 2">
                <image src="../../static/icon/yx.png" class="top-icon"></image>
                <view class="top-tit">有效-已通过</view>
            </view>
            <view class="top" v-if="data.examine == 3">
                <image src="../../static/icon/wx.png" class="top-icon"></image>
                <view class="top-tit">无效</view>
            </view>
            <view class="box" v-if="data.examine == 3 && data.report_reason">
                <view class="wxyy">无效原因</view>
                <view class="wxyy-text">{{data.report_reason}}</view>
            </view>
            <view class="box">
                <view class="item name">
                    <view class="item-l">客户姓名：</view>
                    <view class="u-flex-1">{{data.name}}</view>
                </view>
                <view class="item">
                    <view class="item-l">客户性别</view>
                    <view class="u-flex-1">{{data.gender == 1 ? '男' : '女'}}</view>
                </view>
                <view class="item">
                    <view class="item-l">手机号</view>
                    <view class="u-flex-1">{{data.phone}}</view>
                </view>
                <view class="item" v-if="data.id_number">
                    <view class="item-l">身份证号</view>
                    <view class="u-flex-1">{{data.id_number}}</view>
                </view>
                <view class="item">
                    <view class="item-l">楼盘名称</view>
                    <view class="u-flex-1 u-flex">
                        <view class="u-flex-1">{{data.pro_name}}</view>
                        <view class="btn-b" v-if="type == 1" @click="againReport">重新报备</view>
                    </view>
                </view>
                <view class="item">
                    <view class="item-l">报备时间</view>
                    <view class="u-flex-1">{{data.report_time}}</view>
                </view>
                <view class="item" v-if="data.e_report_time">
                    <view class="item-l">审核通过时间</view>
                    <view class="u-flex-1">{{data.e_report_time}}</view>
                </view>
                <view class="item">
                    <view class="item-l">项目驻场</view>
                    <view class="u-flex-1">{{data.resident_name}}</view>
                </view>
                
                <!-- <view class="border-t u-m-t-20" v-if="data.visit_img && data.visit_img[0] && data.visit_img[0].image">
                    <view class="title">到访单</view>
                    <view class="img-box">
                        <image :src="data.visit_img[0].image" class="up-photo" @click="doPreview(data.visit_img[0].image)"></image>
                    </view>
                </view>
                <view class="border-t u-m-t-20" v-if="data.group_img && data.group_img[0] && data.group_img[0].image">
                    <view class="title">三方合影</view>
                    <view class="img-box">
                        <image :src="data.group_img[0].image" class="up-photo" @click="doPreview(data.group_img[0].image)"></image>
                    </view>
                </view> -->
                
                <view class="border-t u-m-t-20">
                    <!-- <template v-if="type == 1"> -->
                        <view class="title">上传到访单</view>
                        <view class="img-box">
							<view class="u-rela" v-for="(item, index) in visitImg" :key="index" v-if="visitImg.length > 0">
								<image :src="item.image" class="up-photo" @click="doPreview(visitImg, index)"></image>
								<view class="del-icon" v-if="data.examine == 2" @click.stop="delImg(1,index)">删除</view>
							</view>
                            <image src="../../static/image/up_photo.png" class="up-photo" 
								v-if="data.examine == 2 && visitImg.length < 9" @click="chooseImg(1)"></image>
                        </view>
                        <view class="title">上传三方合影</view>
                        <view class="img-box">
							<view class="u-rela" v-for="(item, index) in groupImg" :key="index" v-if="groupImg.length > 0">
								<image :src="item.image" class="up-photo" @click="doPreview(groupImg, index)"></image>
								<view class="del-icon" v-if="data.examine == 2" @click.stop="delImg(2,index)">删除</view>
							</view>
                            <image src="../../static/image/up_photo.png" class="up-photo"
								v-if="data.examine == 2 && groupImg.length < 9" @click="chooseImg(2)"></image>
                        </view>
                    <!-- </template> -->
                    <template v-if="type == 2 && data.examine == 2">
                        <view class="title">上传认购单</view>
						<view class="img-box">
							<view class="u-rela" v-for="(item, index) in buyImg" :key="index" v-if="buyImg.length > 0">
								<image :src="item.image" class="up-photo" @click="doPreview(buyImg, index)"></image>
								<view class="del-icon" v-if="data.examine == 2" @click.stop="delImg(3,index)">删除</view>
							</view>
						    <image src="../../static/image/up_photo.png" class="up-photo" 
								v-if="data.examine == 2 && buyImg.length < 9" @click="chooseImg(3)"></image>
						</view>
                    </template>
                </view>
            </view>
            
            <!-- 订单轨迹 -->
            <view class="box">
                <view class="title2">订单轨迹</view>
                <u-time-line>
                	<u-time-line-item v-for="(item, index) in data.order" :key="index">
                		<template v-slot:content>
                			<view>
                				<view class="context" :class="{active : index == 0}">{{item.msg}}</view>
                				<view class="u-order-time time">更新时间：{{item.time}}</view>
                			</view>
                		</template>
                	</u-time-line-item>
                </u-time-line>
            </view>
            
			<view class="btn u-m-b-30" v-if="data.examine == 2" @click="$noMultipleClicks(doSubmit)">立即提交</view>
			<view class="btn btn2 u-m-b-30" v-if="type == 2 && data.examine == 2" @click="$noMultipleClicks(edit)">确认修改</view>
            
            <view class="u-p-t-80" v-show="show">
                <canvas :style="{width: cwidth,height: cheight}" canvas-id="Canvas" id="Canvas"></canvas>
            </view>
        </view>  
    </view>
</template>

<script>
    import { API_URL } from '@/static/js/common.js';
    export default {
        data() {
            return {
                noClick:true,//连点
                show: false,
                URL: API_URL, //上传图片用的
                visitImg: [],//到访单
                visitImgId: '',
                groupImg: [],//三方合影
                groupImgId: '',
                buyImg: [],//认购单
                buyImgId: '',
                cwidth: '',//画布宽
                cheight: '',//画布高
                urls: '',
                urlsArr: [],
                address: {},
                latitude: '',
                longitude: '',
                
                type: 1,
                id: '',
                data: {},
            };
        },
        onLoad(option) {
            this.type = option.type
            this.id = option.id
            
            this.$getLocation((latitude,longitude) => {
                // console.log('000',latitude, longitude)
                this.latitude = latitude
                this.longitude = longitude
                this.getAppLocation()
            })
			
			this.getData()
        },
        onShow() {
            
        },
        methods: {
            delImg(num,index) {
                if (num == 1) {
					this.visitImg.splice(index,1)
                } else if (num == 2) {
					this.groupImg.splice(index,1)
                } else if (num == 3) {
					this.buyImg.splice(index,1)
                }
            },
            
            // 预览图片
            doPreview(img ,index) {
            	var arr = [];
				img.forEach(cur => {
					arr.push(cur.image)
				})
				uni.previewImage({
				    urls: arr,
					current: index,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							uni.downloadFile({
								url: arr[index], //仅为示例，并非真实的资源
								success: (res) => {
									console.log(res)
									if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
										    filePath: res.tempFilePath, //不支持网络地址
										    success: function () {
										        uni.showToast({
										            title: '保存图片到相册成功',
										        });
										    }
										});
									}
								}
							});
						}
					}
				});
            },
			
			// 确认修改
			edit() {
				let url = '', promise = {}, visitImgId = [], groupImgId = [], buyImgId = []
				
				if (this.visitImg.length <= 0) {
				    this.$toast('请上传到访单');
				    return
				}
				if (this.groupImg.length <= 0) {
				    this.$toast('请上传三方合影');
				    return
				}
				
				this.visitImg.forEach(cur => {
					visitImgId.push(cur.id)
				})
				this.groupImg.forEach(cur => {
					groupImgId.push(cur.id)
				})
				
				if (this.buyImg && this.buyImg.length > 0) {
					this.buyImg.forEach(cur => {
						buyImgId.push(cur.id)
					})
				}
				
				url = 'update_reporting_detail'
				promise = {
				    user_token: this.$getSync('userToken'),
				    id: this.id,//报备id
				    buy_img_ids: buyImgId.join(',') || '',//认购单
					visit_img_ids: visitImgId.join(','),//到访单
					group_img_ids: groupImgId.join(','),//三方合影
				}
				
				this.$ajax(url, promise).then(ret => {
				    if (ret.success == 1000) {
				        this.$toast('提交成功');
				        setTimeout(() => {
				            uni.$emit('KEHU')
				            this.$backT()
				        }, 500)
				    } else {
				        this.$toast(ret.msg);
				    }
				});
			},
			
            // 立即提交
            doSubmit() {
                let url = '', promise = {}, visitImgId = [], groupImgId = [], buyImgId = []
                // 到访
                if (this.type == 1) {
                    if (this.visitImg.length <= 0) {
                        this.$toast('请上传到访单');
                        return
                    }
                    if (this.groupImg.length <= 0) {
                        this.$toast('请上传三方合影');
                        return
                    }
					this.visitImg.forEach(cur => {
						visitImgId.push(cur.id)
					})
					this.groupImg.forEach(cur => {
						groupImgId.push(cur.id)
					})
					
                    url = 'come_to_visit'
                    promise = {
                        user_token: this.$getSync('userToken'),
                        id: this.id,//报备id
                        visit_img_ids: visitImgId.join(','),//到访单
                        group_img_ids: groupImgId.join(','),//三方合影
                    }
                }
                // 认购
                if (this.type == 2) {
					if (this.visitImg.length <= 0) {
					    this.$toast('请上传到访单');
					    return
					}
					if (this.groupImg.length <= 0) {
					    this.$toast('请上传三方合影');
					    return
					}
					if (this.buyImg.length <= 0) {
					    this.$toast('请上传认购单');
					    return
					}
					this.visitImg.forEach(cur => {
						visitImgId.push(cur.id)
					})
					this.groupImg.forEach(cur => {
						groupImgId.push(cur.id)
					})
					this.buyImg.forEach(cur => {
						buyImgId.push(cur.id)
					})
                    url = 'subscribe_for'
                    promise = {
                        user_token: this.$getSync('userToken'),
                        id: this.id,//报备id
                        buy_img_ids: buyImgId.join(','),//认购单
						visit_img_ids: visitImgId.join(','),//到访单
						group_img_ids: groupImgId.join(','),//三方合影
                    }
                }
                this.$ajax(url, promise).then(ret => {
                    if (ret.success == 1000) {
                        this.$toast('提交成功');
                        setTimeout(() => {
                            uni.$emit('KEHU')
                            this.$backT()
                        }, 500)
                    } else {
                        this.$toast(ret.msg);
                    }
                });
            },
            // 重新报备
            againReport() {
                var obj = {
                    id: this.data.pro_id,
                    name: this.data.pro_name,
                    id_status: this.data.id_status,
                    
                    username: this.data.name,
                    phone: this.data.phone,
                    gender: this.data.gender,
                    id_number: this.data.id_number,
                    remark: this.data.remark,
                }
                this.$gTo('/pages/index/report?nitem=' + JSON.stringify(obj) + '&again=1')
            },
            // 获取详情
            getData() {
                this.$ajax('reporting_detail', {
                    user_token: this.$getSync('userToken'),
                    id: this.id,//报备id
                }).then(ret => {
                    if (ret.success == 1000) {
                        this.data = ret.detail
						if (this.data.visit_img && this.data.visit_img[0] && this.data.visit_img[0].image) {
							this.visitImg = this.data.visit_img //到访单
						}
						if (this.data.group_img && this.data.group_img[0] && this.data.group_img[0].image) {
							this.groupImg = this.data.group_img //三方合影
						}
						if (this.data.buy_img && this.data.buy_img[0] && this.data.buy_img[0].image) {
							this.buyImg = this.data.buy_img //认购单
						}
                    } else {
                        this.$toast(ret.msg);
                    }
                });
            },
            
            getAppLocation() {
                const _this = this;
                this.$amapPlugin.getRegeo({
                    location: `${_this.longitude},${_this.latitude}`,
                	success: res => {
                        console.log('周边',res)
                        _this.address = res[0].name || res[0].desc
                	},
                	fail: err => {
                		console.log('失败',err)
						_this.address = '定位失败，请检查网络和权限设置！'
                	}
                });
            },
            
            // 上传图片
            chooseImg(num) {
                var _this = this, sType = [], count = 1
                if (num == 2) {
					count = 1
                    sType = ['album', 'camera']
                } else {
					count = 9
                    sType = ['album', 'camera']
                }
                _this.show = true
                var context = uni.createCanvasContext('Canvas', this)
                uni.chooseImage({
                    count: count, //默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: sType, // 相机拍照 album 相册、camera 拍照
                    success: (res) => {
                        console.log('res',res)
						
                        if (num == 1 || num == 3) {
							const tempFilePaths = res.tempFilePaths;
							for (let i = 0; i < tempFilePaths.length; i++) {
								uni.uploadFile({
								    url: _this.URL + 'api/upload_image', //仅为示例，并非真实接口地址。
								    filePath: res.tempFilePaths[i],
								    name: 'image',
								    formData:{module: 'api'},
								    success: result => {
								        console.log(result)
								        let data = JSON.parse(result.data).detail; //后台返回的路径data.attach_uri
								        if (num == 1) {
											_this.visitImg.push({
												image: data.image,
												id: data.image_id
											})
								        } else if (num == 3) {
											_this.buyImg.push({
												image: data.image,
												id: data.image_id
											})
								        }
								    },
								    fail: err => {
								        console.log('err', err)
								    }
								});
							}
                        } else if (num == 2) {
                            // 加水印
                            uni.getImageInfo({
                                src: res.tempFilePaths[0],
                                success: (image) => {
                                    console.log('image',image)
                                    _this.cwidth = image.width + 'px'
                                    _this.cheight = image.height + 'px'
                                    setTimeout(() => {
                                        context.width = _this.cwidth;
                                        context.height = _this.cheight;
                                        // 填充一个矩形 x轴 y轴
                                        context.fillRect(0, 0, _this.cwidth, _this.cheight);
                                        // 绘制图像到画布，将图片src放到cancas内，宽高为图片大小
                                        context.drawImage(res.tempFilePaths[0], 0, 0, image.width, image.height)
                                        
                                        // let time = new Date()
                                        // let nowTime = time.toLocaleString()
                                        let date = new Date();
                                        let year = date.getFullYear();
                                        let month = date.getMonth() + 1;
                                        let day = date.getDate();
                                        let hour = date.getHours();
                                        let minute = date.getMinutes();
                                        let second = date.getSeconds();
                                        let time = year + '-' + this.addZero(month) + '-' + this.addZero(day) + ' ' + this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
                                        
                                        context.beginPath();
                                        context.setFontSize(45);
                                        // context.setFillStyle("rgba(194, 190, 60, 0.6)");
										context.setFillStyle("rgba(255, 5, 5, 1)");
                                        // 左上角
                                        // context.fillText(time, 10, 35)//当前时间
                                        // context.fillText(_this.address, 10, 65)//当前定位地址
                                        // 左下角
                                        // context.fillText(time, 10, image.height - 55)//当前时间
                                        // context.fillText(_this.address, 10, image.height - 15)//当前定位地址
                                        // 中间
                                        context.fillText(time, image.width / 5, image.height / 2.3)//当前时间
                                        context.fillText(_this.address,image.width / 5, image.height / 2)//当前定位地址
                                        
                                        uni.showLoading({title: '上传中...',})
                                        context.draw(false, () => {
                                            setTimeout(() => {
                                                uni.canvasToTempFilePath({
                                                    canvasId: "Canvas",
                                                    fileType: 'jpg' || 'png',
                                                    success: (path) => {
                                                        console.log('path',path)
                                                        _this.urls = path.tempFilePath
                                                        _this.uploadImg(num)
                                                        uni.hideLoading()
                                                    }
                                                }, this)
                                            }, 500)
                                        })
                                    }, 1000)
                                }
                            })
                        }
                    }
                });
            },
            addZero(s) {
                return s < 10 ? ('0' + s) : s;
            },
            
            // 上传
            uploadImg(num) {
                let _this = this
                uni.uploadFile({
                    url: _this.URL + 'api/upload_image', //仅为示例，并非真实接口地址。
                    filePath: _this.urls,
                    name: 'image',
                    formData:{module: 'api'},
                    success: result => {
                        console.log(result)
                        let data = JSON.parse(result.data).detail; //后台返回的路径data.attach_uri
                        if (num == 2) {
							_this.groupImg.push({
								image: data.image,
								id: data.image_id
							})
							_this.show = false
							_this.cwidth = 0
							_this.cheight = 0
                        }
                        console.log(_this.show,_this.cwidth,_this.cheight)
                    },
                    fail: err => {
                        console.log('err', err)
                    }
                });
            },
        }
    };
</script>

<style lang="scss">
    
    
    page{
        background-color: #f5f5f5;
    }
    .class1 {
        width: 100vw;
    	height: 400rpx;
    	background: linear-gradient(180deg, #3a9cf6, #3fafec, #f5f5f5);
        padding: 20rpx;
    }
    .top{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 0 0 35rpx 25rpx;
    }
    .top-icon{
        width: 69rpx;
        height: 69rpx;
        margin-right: 25rpx;
    }
    .top-tit{
        font-size: 42rpx;
        color: #fff;
    }
    
    .box{
        background-color: #fff;
        border-radius: 20rpx;
        margin-bottom: 20rpx;
        padding: 35rpx 30rpx;
    }
    .wxyy{
        font-size: 30rpx;
        color: #fe6155;
        padding-bottom: 10rpx;
    }
    .wxyy-text{
        font-size: 24rpx;
        word-break: break-all;
        white-space: pre-line;
    }
    .item{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10rpx;
    }
    .name{
        font-size: 30rpx;
        font-weight: bold;
    }
    .item-l{
        width: 24.5vw;
    }
    .btn-b{
        padding: 15rpx 17rpx;
        border-radius: 10rpx;
        background-color: #ffecd2;
        font-size: 24rpx;
        line-height: 1;
        color: #803906;
        margin-left: 10rpx;
    }
    .border-t{
        border-top: 2rpx solid #e6e6e6;
    }
    .title{
        font-size: 28rpx;
        font-weight: bold;
        padding: 28rpx 0 20rpx;
    }
    .title2{
        font-size: 28rpx;
        font-weight: bold;
        padding-bottom: 20rpx;
    }
    .img-box{
        // width: 168rpx;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
        // position: relative;
    }
    .up-photo{
        width: 168rpx;
        height: 168rpx;
        margin-right: 15rpx;
        margin-bottom: 15rpx;
    }
    .del-icon{
        font-size: 22rpx;
        color: #fff;
        background: rgba(0, 0, 0, .5);
        padding: 5rpx 8rpx;
        position: absolute;
        right: 14rpx;
        bottom: 14rpx;
    }
    
    .context{
        font-size: 28rpx;
        font-weight: bold;
    }
    .active{
        color: #ff6539;
    }
    .time{
        font-size: 24rpx;
        color: #595959;
        padding-top: 5rpx;
    }
    
    .btn{
        color: #fff;
        font-size: 34rpx;
        text-align: center;
        padding: 25rpx;
        margin: 40rpx 0;
        background-color: #00a1e9;
        border-radius: 50rpx;
    }
	.btn2{
		background-color: #a8a6a6;
	}
    
</style>
